/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.netbeans.xml.schema.accountschema.Users;
import org.netbeans.xml.schema.accountschema.Users.User;
import generated.ShoppingCart;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Red Army
 */
@WebServlet(name = "LoginController", urlPatterns = {"/LoginController"})
public class UserController extends HttpServlet {

    String errorPage = "error.html";
    String backPage = "index.jsp";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        try (PrintWriter out = response.getWriter()) {
            String action = request.getParameter("btnAction");
            String url = errorPage;
            String username = request.getParameter("txtUsername");
            String password = request.getParameter("txtPassword");
            switch (action) {
                case "Login": {

                    // <editor-fold defaultstate="collapsed" desc="Using DOM to querry.">
                    /* Using DOM to querry
                     **/
                    //DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    //DocumentBuilder db = dbf.newDocumentBuilder();
                    //String file = getServletContext().getRealPath("/") + "WEB-INF/accounts.xml";
                    //Document doc = db.parse(new File(file));


                    //XPathFactory xpf = XPathFactory.newInstance();
                    //XPath xpath = xpf.newXPath();
                    //String xpExpression = "/ns0:users/ns0:user[contains(@ID, '" + username + "')]";

                    //NodeList list = (NodeList) xpath.evaluate(xpExpression,
                    //        doc, XPathConstants.NODESET);

                    //if (list.getLength() > 0) {
                    //    HttpSession session = request.getSession(true);
                    //    session.setAttribute("USER", username);
                    //    url = backPage;
                    //}
                    //</editor-fold>

                    // <editor-fold defaultstate="collapsed" desc="Login logics.">
                    HttpSession session = request.getSession(true);
                    User checkLoggedInUser = (User) session.getAttribute("USER");
                    if (!(checkLoggedInUser == null)) {
                        if (!checkLoggedInUser.getID().equals(username)) {
                            url = errorPage;
                        } else {
                            url = backPage;
                        }
                    } else {
                        JAXBContext jc = JAXBContext.newInstance("org.netbeans.xml.schema.accountschema");
                        Unmarshaller u = jc.createUnmarshaller();
                        File f = new File(getServletContext().getRealPath("/") + "WEB-INF/users.xml");

                        Users users = (Users) u.unmarshal(new FileInputStream(f));
                        url = "login.jsp";
                        if (!users.getUser().isEmpty()) {
                            for (int i = 0; i < users.getUser().size(); i++) {
                                User user = (User) users.getUser().get(i);
                                if (user.getID().equals(username)) {
                                    if (user.getPassword().equals(password)) {
                                        //HttpSession session = request.getSession(true);
                                        session.setAttribute("USER", user);
                                        url = backPage;
                                        break;
                                    } else {
                                        url = "login.jsp";
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, response);
                    // </editor-fold>
                    break;
                }
                case "Forgot Password ?": {
                    url = errorPage;
                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, response);
                    break;
                }
                case "AccountSetting": {

                    url = "user.jsp";
                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, response);
                    break;
                }
                case "Log Out": {
                    
                    HttpSession session = request.getSession(true);
                    //session.invalidate();
                    session.setAttribute("USER", null);
                    url = backPage;

                    File fi = new File(getServletContext().getRealPath("/WEB-INF/" + session.getId() + "_shoppingCart.xml"));
                    servlet.Process.writeToFile(fi, new Vector(), new ShoppingCart());
                    
                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, response);
                    break;
                }
                case "Update": {

                    //<editor-fold defaultstate="collapsed" desc="Initial Enviroment.">
                    JAXBContext jc = JAXBContext.newInstance("org.netbeans.xml.schema.accountschema");
                    Unmarshaller u = jc.createUnmarshaller();
                    File f = new File(getServletContext().getRealPath("/") + "WEB-INF/users.xml");

                    Users users = (Users) u.unmarshal(new FileInputStream(f));
                    //</editor-fold>

                    //<editor-fold defaultstate="collapsed" desc="Edit User Info.">
                    if (!users.getUser().isEmpty()) {
                        // Check for conflict ID
                        for (int i = 0; i < users.getUser().size(); i++) {
                            User user = (User) users.getUser().get(i);
                            if (user.getID().equals(username)) {

                                String currentPassword = request.getParameter("txtCurrentPassword");
                                String newPassword = request.getParameter("txtNewPassword");
                                String confirmPassword = request.getParameter("txtConfirmPassword");
                                String email = request.getParameter("txtNewEmail");
                                String address = request.getParameter("txtNewAddress");
                                BigInteger phone = BigInteger.valueOf(Long.parseLong(request.getParameter("txtNewPhone")));
                                HttpSession session = request.getSession();
                                User currentUser = (User) session.getAttribute("USER");

                                if (confirmPassword.equals(newPassword) && currentPassword.equals(currentUser.getPassword())) {
                                    user.setPassword(newPassword);
                                    user.setAddress(address);
                                    user.setEmail(email);
                                    user.setPhone(phone);
                                    //</editor-fold>
                                    //<editor-fold defaultstate="collapsed" desc="JAXB Mashall.">
                                    JAXBContext ctx = JAXBContext.newInstance(users.getClass());
                                    Marshaller mar = ctx.createMarshaller();
                                    mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
                                    mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                                    mar.marshal(users, f);
                                    url = backPage;
                                } else {
                                    url = errorPage;
                                }
                                break;
                            }
                        }
                        //</editor-fold>
                    }

                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, response);
                    break;

                }
                case "Register": {
                    //<editor-fold defaultstate="collapsed" desc="Initial Enviroment.">
                    JAXBContext jc = JAXBContext.newInstance("org.netbeans.xml.schema.accountschema");
                    Unmarshaller u = jc.createUnmarshaller();
                    File f = new File(getServletContext().getRealPath("/") + "WEB-INF/users.xml");

                    Users users = (Users) u.unmarshal(new FileInputStream(f));
                    //</editor-fold>

                    //<editor-fold defaultstate="collapsed" desc="Check for Conflitc User ID.">
                    if (!users.getUser().isEmpty()) {
                        // Check for conflict ID
                        for (int i = 0; i < users.getUser().size(); i++) {
                            User user = (User) users.getUser().get(i);
                            if (user.getID().equals(username)) {
                                url = errorPage;
                                break;
                            }
                        }
                        //</editor-fold>

                        //<editor-fold defaultstate="collapsed" desc="Add New User.">

                        String newUsername = request.getParameter("txtNewUsername");
                        String newPassword = request.getParameter("txtNewPassword");
                        String confirmPassword = request.getParameter("txtConfirmPassword");
                        String email = request.getParameter("txtNewEmail");
                        String address = request.getParameter("txtNewAddress");
                        BigInteger phone = BigInteger.valueOf(Long.parseLong(request.getParameter("txtNewPhone")));

                        if (confirmPassword.equals(newPassword)) {

                            User newUser = new User(email, address, phone, newUsername, newPassword);
                            users.getUser().add(newUser);

                            JAXBContext ctx = JAXBContext.newInstance(users.getClass());
                            Marshaller mar = ctx.createMarshaller();
                            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
                            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                            mar.marshal(users, f);
                            url = backPage;
                        } else {
                            url = errorPage;
                        }

                        //</editor-fold>
                    }

                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, response);
                    break;
                }
                default: {
                    url = errorPage;
                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, response);
                    break;
                }
            }

        } catch (JAXBException ex) {
            ex.printStackTrace();
        } /*
        catch (XPathExpressionException ex) {
        ex.printStackTrace();
        } catch (SAXException ex) {
        ex.printStackTrace();
        } catch (ParserConfigurationException ex) {
        ex.printStackTrace();
        } 
         */ catch (ServletException ex) {
            ex.printStackTrace();
        } catch (NumberFormatException ex) {
            ex.printStackTrace();
            response.sendRedirect(errorPage);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
